package com.restkeeper.controller;

import com.restkeeper.entity.EnterpiseAccount;
import com.restkeeper.service.IEnterpiseAccountService;
import com.restkeeper.vo.AddEnterpiseAccountVO;
import com.restkeeper.vo.ResetPwdVO;
import com.restkeeper.vo.UpdateEnterpiseAccountVO;
import com.restkeeper.response.page.PageVO;
import com.restkeeper.utils.AccountStatus;
import com.restkeeper.utils.Result;
import com.restkeeper.utils.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
    * 企业账号管理 前端控制器
    * </p>
 */
@Slf4j
@Api(tags = {"企业账号管理"})
@RestController
@RequestMapping("/enterprise")
public class EnterpriseAccountController {
    @Reference(version = "1.0.0", check=false)
    private IEnterpiseAccountService enterpiseAccountService;

    /**
     * 查询分页数据
     */
    @ApiOperation(value = "查询企业账号(支持分页)")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="path", name = "page", value = "当前页码", required = false, dataType = "Integer"),
        @ApiImplicitParam(paramType="path", name = "pageSize", value = "分大小", required = false, dataType = "Integer"),
        @ApiImplicitParam(paramType="query", name = "name", value = "支持企业名称查询", required = false, dataType = "String")
    })
    @GetMapping(value = "/pageList/{page}/{pageSize}")
    public PageVO<EnterpiseAccount> findListByPage(@PathVariable int page, @PathVariable int pageSize, @RequestParam(name="name",defaultValue = "",required = false) String name){
   	   return new PageVO<>(enterpiseAccountService.queryPageByName(page,pageSize,name));
    }

    /**
     新增账号
     */
    @ApiOperation(value = "新增账号")
    @PostMapping(value = "/add")
    public boolean add(@RequestBody AddEnterpiseAccountVO enterpiseAccountVO){
        EnterpiseAccount enterpiseAccount= new EnterpiseAccount();
        BeanUtils.copyProperties(enterpiseAccountVO, enterpiseAccount);
        LocalDateTime localDateTime = LocalDateTime.now();
        enterpiseAccount.setApplicationTime(localDateTime);
        LocalDateTime expireTime=null;
        //试用期账号默认七天
        if(enterpiseAccountVO.getStatus()==0) {
            expireTime = localDateTime.plusDays(7);
        }else if(enterpiseAccountVO.getStatus()==1) {
            //到期时间
            expireTime = localDateTime.plusDays(enterpiseAccountVO.getValidityDay());
        }
        if(expireTime!=null){
            enterpiseAccount.setExpireTime(expireTime);
        }
        return enterpiseAccountService.add(enterpiseAccount);
    }




    /**
     * 根据id查询
     */
    @ApiOperation(value = "账户查看")
    @ApiImplicitParam(paramType="query", name = "id", value = "主键", required = true, dataType = "String")
    @GetMapping(value = "/getById/{id}")
    public EnterpiseAccount getById(@PathVariable String id){
        return enterpiseAccountService.getById(id);
    }

    /**
     重置密码
     */
    @ApiOperation(value = "重置密码")
    @PutMapping(value = "/resetPwd")
    public boolean resetPwd(@RequestBody ResetPwdVO resetPwdVO){
        return enterpiseAccountService.resetpwd(resetPwdVO.getId(),resetPwdVO.getPwd());
    }


    @ApiOperation(value = "禁止使用")
    @ApiImplicitParam(paramType="query", name = "id", value = "主键", required = true, dataType = "String")
    @PutMapping(value = "/forbidden/{id}")
    public boolean forbidden(@PathVariable String id){
        EnterpiseAccount enterpiseAccount = enterpiseAccountService.getById(id);
        enterpiseAccount.setStatus(AccountStatus.Forbidden.getStatus());
        return enterpiseAccountService.updateById(enterpiseAccount);
    }

    /**
     * 账号编辑
     */
    @ApiOperation(value = "账号编辑")
    @PutMapping(value = "/update")
    public Result update(@RequestBody UpdateEnterpiseAccountVO enterpiseAccountVO) {
        EnterpiseAccount enterpiseAccount = enterpiseAccountService.getById(enterpiseAccountVO.getEnterpriseId());
        Result result = new Result();
        if (enterpiseAccount == null) {
            result.setStatus(ResultCode.error);
            result.setDesc("修改账户不存在");
            return result;
        }
        // 修改状态要做特殊校验
        if (enterpiseAccountVO.getStatus() != null) {
            if (enterpiseAccountVO.getStatus() == 0 && enterpiseAccount.getStatus() == 1) {
                result.setStatus(ResultCode.error);
                result.setDesc("不能将正式账号改成试用账号");
                return result;
            }
            // 试用期改正式
            if (enterpiseAccountVO.getStatus() == 1 && enterpiseAccount.getStatus() == 0) {
                LocalDateTime now = LocalDateTime.now();
                // 到期时间
                LocalDateTime expireTime = now.plusDays(enterpiseAccountVO.getValidityDay());
                enterpiseAccount.setApplicationTime(now);
                enterpiseAccount.setExpireTime(expireTime);
            }
            // 正式期延期
            if (enterpiseAccountVO.getStatus() == 1 && enterpiseAccount.getStatus() == 1) {
                //如果修改了有效期
                //if(enterpiseAccount.getValidityDay()!=enterpiseAccountVO.getValidityDay()){
                    LocalDateTime now = LocalDateTime.now();
                    enterpiseAccount.setApplicationTime(now);
                    // 到期时间
                    LocalDateTime expireTime = now.plusDays(enterpiseAccountVO.getValidityDay());
                    enterpiseAccount.setExpireTime(expireTime);
               // }
            }
        }
        // 其他字段copy
        BeanUtils.copyProperties(enterpiseAccountVO, enterpiseAccount);
        boolean update = enterpiseAccountService.updateById(enterpiseAccount);
        if (update) {
            result.setStatus(ResultCode.success);
            result.setDesc("修改成功");
            return result;
        } else {
            result.setStatus(ResultCode.error);
            result.setDesc("修改失败");
            return result;
        }
    }

    /**
     * 根据id删除
     */
    @ApiOperation(value = "账户删除")
    @ApiImplicitParam(paramType="query", name = "id", value = "主键", required = true, dataType = "String")
    @DeleteMapping(value = "/deleteById/{id}")
    public boolean delete(@PathVariable String id){
        return enterpiseAccountService.removeById(id);
    }

    /**
     * 根据id恢复
     */
    @ApiOperation(value = "数据恢复")
    @ApiImplicitParam(paramType="query", name = "id", value = "主键", required = true, dataType = "String")
    @PutMapping(value = "/recovery/{id}")
    public boolean recovery(@PathVariable String id){
        return enterpiseAccountService.recovery(id);
    }


    @ApiOperation(value = "启用恢复")
    @ApiImplicitParam(paramType="query", name = "id", value = "主键", required = true, dataType = "String")
    @PutMapping(value = "/enable/{id}")
    public boolean enabled(@PathVariable String id){
        EnterpiseAccount enterpiseAccount = enterpiseAccountService.getById(id);
        if(enterpiseAccount.getValidityDay()==7){
            enterpiseAccount.setStatus(AccountStatus.Trial.getStatus());
        }else if(enterpiseAccount.getValidityDay()>7){
            enterpiseAccount.setStatus(AccountStatus.Official.getStatus());
        }
        return enterpiseAccountService.updateById(enterpiseAccount);
    }

}
